<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set("display_errors", 1);

require_once('config.php');
$program_start = microtime();

$expected = array(
	  'cmd'
	, 'url'
	, 'str'
	, 'str2'
	, 'word_type'
	, 'output'
	, 'search_mode'
	, 'debug'
	, 'source'
	, 'strip_ending'
	, 'normalize'
	, 'cache'
	,	'layout'
	,	'block_limit'
	,	'max_distance'
	,	'database'
);
// Initialize allowed variables
foreach ($expected as $formvar)
	$$formvar = (isset(${"_$_SERVER[REQUEST_METHOD]"}[$formvar])) ? stripslashes(${"_$_SERVER[REQUEST_METHOD]"}[$formvar]) : NULL;

$source = (trim($source) == '' ? 'sample' : $source);
$cache = (trim($cache) == 'true') ? true: false;

require_once('classes/class.misc.php');
require_once('classes/class.mysqli_database.php');
require_once('classes/class.taxamatch.php');
require_once('classes/class.dwca_process.php');

$valid = true;

header('Content-type: application/json');
switch($cmd) {

	case 'loadDwca':
		$db = select_source( $source );
		if($url == '') {
			$valid = false;
			$code = 102;
		}
		if(true != @fopen($url,"r")) {
			$valid = false;
			$code = 103;
		}
		if($valid) {
// 			$sourcePath =  sys_get_temp_dir() . '/' . time() . '.zip';
			$sourcePath = '/var/www/html/taxamatch/api/csv_process/' . time() . '.zip';
			if(!downloadRemoteFile($url,$sourcePath)) {
				$valid = false;$code = 103;
			}

			$dwca = new DwcaProcess($db);
			$dwca->set('sourcePath',$sourcePath);
			$dwca->set('metaFilePath','/var/www/html/taxamatch/api/csv_process/');
			$dwca->set('output_file',md5(@mktime()) . '.csv');
			if($dwca->extractMetaFile()) {
				$dwca->getMetaFile();
				if(!$dwca->processCoreFile()) {
					$valid = false;$code = 105;
				}
			} else {
				$valid = false;$code =104;
			}
		}
		if($valid) {
			print json_encode(array('success' => true, 'url' => 'http://tm.silverbiology.com/taxamatch/api/csv_process/' . $dwca->get('output_file')));
		} else {
			print json_encode(array('success' => false, 'error' => array('code' => $code, 'message' => getError($code))));
		}
		break;
	default:
		print json_encode(array('success' => false, 'error' => array('code' => 101, 'message' => getError(101))));
		break;
}
?>